import React, { useEffect, useState } from 'react';
import { Modal, Button, Form } from 'react-bootstrap';

/**
 * @typedef {Object} FieldSchema
 * @property {string} label - 字段的标签
 * @property {string} type - 字段的类型（如 'text', 'textarea' 等）
 */

/**
 * @typedef {Object.<string, FieldSchema>} EditBoxSchema 字段定义的对象
 */

/**
 * @typedef {() => {}} CloseCallback
 */

/**
 * @typedef {Object} OptionsSchema
 * @property {boolean} withCancel - 是否显示取消按钮
 * @property {boolean} withSubmit - 是否显示提交按钮
 * @property {boolean} withClose - 是否显示关闭按钮
 * @property {string} title - 标题
 * @property {boolean} showModal - 是否显示模态框
 * @property {(formData: object, onClose: CloseCallback) => {}} onSubmit - 提交表单时的回调函数
 * @property {CloseCallback} onClose - 关闭模态框时的回调函数
 */

/**
 * 编辑框组件
 * @param {Object} props - 组件的属性
 * @param {Object.<string, FieldSchema>} props.schema - 字段定义的对象
 * @param {OptionsSchema} props.options - 配置选项
 * @param {Object.<string, string>} props.defaultData - 字段的默认数据
 */
function EditBox({ schema, options, defaultData, showModal }) {
    // TODO 修复相同字段第二次若该字段为空，显示不会清除，仍然显示上次的值
    const [formData, setFormData] = useState({});
    const { onSubmit, onResult, onClose } = options;
    useEffect(() => {
        const initialData = {};
        Object.keys(schema).forEach(key => {
            initialData[key] = defaultData[key] || '';
        });
        Object.assign(initialData, defaultData); // 保留 schema 中未定义的字段
        setFormData(initialData);
    }, [defaultData]);

    const handleChange = (key, value) => {
        setFormData({
            ...formData,
            [key]: value,
        });
    };

    const handleSubmit = () => {
        if (onSubmit) onSubmit(formData, onClose);
    };

    const handleCancel = () => {
        if (onClose) onClose();
    };

    return (
        <Modal show={showModal} onHide={handleCancel}>
            <Modal.Header closeButton={options.withClose}>
                <Modal.Title>{options.title ?? '标题'}</Modal.Title>
            </Modal.Header>
            <Modal.Body>
                <Form>
                    {Object.keys(schema).map(key => {
                        const field = schema[key];
                        return (
                            <Form.Group key={key}>
                                <Form.Label className='mt-2'>{field.label}</Form.Label>
                                {field.type === 'text' && (
                                    <Form.Control
                                        type="text"
                                        value={formData[key]}
                                        onChange={(e) => handleChange(key, e.target.value)}
                                    />
                                )}
                                {field.type === 'textarea' && (
                                    <Form.Control
                                        as="textarea"
                                        value={formData[key]}
                                        onChange={(e) => handleChange(key, e.target.value)}
                                    />
                                )}
                            </Form.Group>
                        );
                    })}
                </Form>
            </Modal.Body>
            <Modal.Footer>
                {options.withCancel && <Button variant="secondary" onClick={handleCancel}>取消</Button>}
                {options.withSubmit && <Button variant="primary" onClick={handleSubmit}>提交</Button>}
            </Modal.Footer>
        </Modal>
    );
}


/*
Sample Data:

{
    title: '编辑诗词',
    schema: {
        // custom data
        title: {
            label: '标题', // required
            type: 'text', // required
            defaultData: '' // not required
        },
        content: {
            label: '内容',
            type: 'textarea',
            defaultData: ''
        },
    },
    options: {
        withCancel: true,
        withSubmit: true,
        withClose: true,
    },
    onSubmit: (data) => {
        console.log('Submit', data);
    },
}
*/

export default EditBox;